import { Space, message } from 'antd'
import React from 'react'
import { useLowCodeStore } from '../../store/lowcode'
import { Component } from '../../types'

import Button from '../../components/button'

const ComponentMap: { [key: string]: any } = {
  Button: Button,
  Space: Space
}

const ComponentEventMap: { [key: string]: any[] } = {
  Button: [
    {
      id: 1,
      name: 'onClick'
    }
  ]
}

const ProdStage: React.FC = () => {
  const { components } = useLowCodeStore()

  function renderComponents(components: Component[]): React.ReactNode {
    return components.map((component: Component) => {
      console.warn('component', component)

      if (!ComponentMap[component.name]) {
        return null
      }

      if (ComponentMap[component.name]) {
        return React.createElement(
          ComponentMap[component.name],
          {
            key: component.id,
            id: component.id,
            ...component.props,
            ...handleEvent(component)
          },
          component.props.children || renderComponents(component.children || [])
        )
      }

      return null
    })
  }

  // 处理事件
  function handleEvent(component: Component) {
    const props: any = {}

    if (ComponentEventMap[component.name]) {
      ComponentEventMap[component.name].forEach((event) => {
        const eventConfig = component.props[event.name]

        if (eventConfig) {
          const { type, config } = eventConfig
          props[event.name] = () => {
            if (type === 'showMessage') {
              if (config.type === 'success') {
                message.success(config.text)
              } else if (config.type === 'error') {
                message.error(config.text)
              }
            }
          }
        }
      })
    }

    return props
  }

  return <div>{renderComponents(components)}</div>
}

export default ProdStage
